//
//  WBHomeController.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/8/29.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit
import YYModel
class WBHomeController: WBVisitorTableViewController {

    //var statusArray : [WBStatus]?
    lazy var homeViewModel : WBHomeViewModel = WBHomeViewModel()
    override func viewDidLoad() {
//        super.viewDidLoad()
       
            if userInfo == false
        {
            visitorView.setVisitorViewInfo(imgName: nil, message: "关注一些人，回这里看看有什么惊喜")
            return
        }
        self.tableView.register(WBStatusCell.classForCoder(), forCellReuseIdentifier: "cellid")
        
        setUI()
        self.loadData()
    }

    func loadData()
    {
        homeViewModel.loadData(isPullUp: pullUpView.isAnimating) { (isSuccess,count) in
            if isSuccess
            {
                self.tableView.reloadData()
            }
            else
            {
                print("加载错误")
            }
            if !self.pullUpView.isAnimating{
                self.showTipLabel(count: count)
            }
            //结束刷新
            self.pullUpView.stopAnimating()
            self.wbRefreshControl.endRefreshing()
        }
    }
    
    private func showTipLabel(count: Int) {
        
        if pullDownTipLabel.isHidden == false {
            // 如果当前已经再显示，那么就直接返回
            return
        }
        // 让其显示出来
        pullDownTipLabel.isHidden = false
        // 要显示的字符串
        let str = count == 0 ? "没有微博数据" : "\(count) 条微博数据"
        // 设置显示的字符串
        pullDownTipLabel.text = str
        
        UIView.animate(withDuration: 1, animations: {
            // 将其显示出来
            self.pullDownTipLabel.transform = CGAffineTransform.init(translationX: 0, y: self.pullDownTipLabel.frame.height)
        }) { (_) in
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                // 让其回去
                self.pullDownTipLabel.transform = CGAffineTransform.identity
                }, completion: { (_) in
                    // 所有动画执行完毕之后，再次隐藏
                    self.pullDownTipLabel.isHidden = true
            })
        }
    }

    func setUI()
    {
        /*
        let button = UIButton()
        button.setImage(#imageLiteral(resourceName: "navigationbar_friendsearch"), for: UIControlState.normal)
        button.setImage(#imageLiteral(resourceName: "navigationbar_friendsearch_highlighted"), for: UIControlState.highlighted)
        button.sizeToFit()
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
         */
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: nil, action: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(pop))
        //预估行高
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 200
        //关闭分割线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        
        tableView.tableFooterView = pullUpView
        tableView.addSubview(wbRefreshControl)
        wbRefreshControl.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged)
        //添加下拉刷新提示控件
        self.navigationController?.view.insertSubview(pullDownTipLabel, belowSubview: self.navigationController!.navigationBar)
        pullDownTipLabel.frame.origin.y = self.navigationController!.navigationBar.frame.maxY - pullDownTipLabel.frame.height
        
    }
    
    func pop()
    {
        let vc = WBTempController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    ///懒加载控件
    lazy var pullUpView : UIActivityIndicatorView = {
//        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
//        view.color = UIColor.black
//        return view
        let pullUpView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.whiteLarge)
        // 设置颜色
        pullUpView.color = UIColor.black
        return pullUpView

    }()
    lazy var wbRefreshControl : WBRefreshControl = WBRefreshControl()
    //下拉刷新提示
    lazy var pullDownTipLabel : UILabel = {
       let label = UILabel(textColor: UIColor.white, fontSize: 14)
        label.backgroundColor = RandomColor
        label.textAlignment = .center
        label.frame.size = CGSize(width: WBScreenW, height: 35)
        label.isHidden = true
        return label
    }()
    /*
    private func loadData()
    {
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let parameters = [
            "access_token":WBUserAccountViewModel.sharedModel.account?.access_token ?? ""
        ]
        
        WBNetworkTools.sharedTools.request(method: .Get, urlString: urlString, parameters: parameters) { (responce, error) in
            if error != nil
            {
                print("请求错误：\(error)")
                return
            }
            
            //print(responce!)
            guard let dictArray = (responce! as! [String:Any])["statuses"] as? [[String : Any]] else
            {
                return
            }
            let modelArr = NSArray.yy_modelArray(with: WBStatus.classForCoder(), json: dictArray) as! [WBStatus]
            
            self.statusArray = modelArr
            self.tableView.reloadData()
        }
    }
    */
    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.homeViewModel.statusArray?.count ?? 0
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellid", for: indexPath) as! WBStatusCell

        let model = self.homeViewModel.statusArray![indexPath.row]
        cell.statusViewModel = model

        return cell
    }
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == homeViewModel.statusArray!.count - 1 && pullUpView.isAnimating == false{
            pullUpView.startAnimating() 
            loadData()
        }
    }
    

    
}
